import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store/index.js'
import ModalApi from '@/components/SwModal/api.js'
import { Http } from '@/service/Http/index.js'
import EventBus from '@/service/EventBus.js'
import LoginService from '@/service/LoginService.js'
import Config from '@/global/config.js'

Vue.use(Router)

let router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'home',
      component: resolve => require(['@/pages/home/index'], resolve),
      meta: {
        needSetPIN: true
      }
    },
    {
      path: '/news/index',
      component: resolve => require(['@/pages/news/index'], resolve),
      meta: {
        needSetPIN: true
      }
    },
    {
      path: '/news/index/:currentPage',
      component: resolve => require(['@/pages/news/index'], resolve),
      meta: {
        needSetPIN: true
      }
    },
    {
      path: '/news/detail',
      component: resolve => require(['@/pages/news/detail'], resolve),
      meta: {
        needSetPIN: true
      }
    },
    {
      path: '/news/announcement',
      component: resolve => require(['@/pages/news/announcement'], resolve),
      meta: {
        needSetPIN: true
      }
    },
    {
      path: '/news/announcement_details',
      component: resolve => require(['@/pages/news/announcement_details'], resolve),
      meta: {
        needSetPIN: true
      }
    },
    {
      path: '/user/login',
      component: resolve => require(['@/pages/user/login'], resolve)
    },
    {
      path: '/user/register',
      component: resolve => require(['@/pages/user/register'], resolve)
    },
    {
      path: '/help/privacyPolicy',
      component: resolve => require(['@/pages/help/privacyPolicy'], resolve),
      meta: {
        needSetPIN: true
      }
    },
    {
      path: '/help/termsOfUse',
      component: resolve => require(['@/pages/help/termsOfUse'], resolve),
      meta: {
        needSetPIN: true
      }
    },
    {
      path: '/user/findPasswordStep1',
      component: resolve => require(['@/pages/user/findPasswordStep1'], resolve)
    },
    {
      path: '/user/findPasswordStep2',
      component: resolve => require(['@/pages/user/findPasswordStep2'], resolve)
    },
    {
      path: '/assets',
      name: 'assetsHome',
      component: resolve => require(['@/pages/assets/index'], resolve),
      meta: {
        needLogin: true,
        needSetPIN: true
      }
    },
    {
      path: '/assets/records',
      name: 'records',
      component: resolve => require(['@/pages/assets/records'], resolve),
      meta: {
        needLogin: true,
        needSetPIN: true
      }
    },
    {
      path: '/assets/address',
      name: 'address',
      component: resolve => require(['@/pages/assets/address'], resolve),
      meta: {
        needLogin: true,
        needSetPIN: true
      }
    },
    {
      path: '/assets/bankcard',
      name: 'bankcard',
      component: resolve => require(['@/pages/assets/bankcard'], resolve),
      meta: {
        needLogin: true,
        needSetPIN: true
      }
    },
    {
      path: '/assets/remitInfo',
      name: 'remitInfo',
      component: resolve => require(['@/pages/assets/remitInfo'], resolve),
      meta: {
        needLogin: true,
        needSetPIN: true
      }
    },
    {
      path: '/assets/escrow',
      name: 'escrow',
      component: resolve => require(['@/pages/assets/escrow'], resolve),
      meta: {
        needLogin: true,
        needSetPIN: true
      }
    },
    {
      path: '/safety',
      name: 'safetyHome',
      component: resolve => require(['@/pages/safety/index'], resolve),
      meta: {
        needLogin: true,
        needSetPIN: true
      }
    },
    {
      path: '/safety/setPin',
      name: 'setPin',
      component: resolve => require(['@/pages/safety/setPin'], resolve)
    },
    {
      path: '/safety/strategy',
      name: 'strategy',
      component: resolve => require(['@/pages/safety/strategy'], resolve),
      meta: {
        needLogin: true,
        needSetPIN: true
      }
    },
    {
      path: '/safety/log',
      name: 'log',
      component: resolve => require(['@/pages/safety/log'], resolve),
      meta: {
        needLogin: true,
        needSetPIN: true
      }
    },
    {
      path: '/help/rate',
      component: resolve => require(['@/pages/help/rate'], resolve),
      meta: {
        needSetPIN: true
      }
    },
    {
      path: '/help/about',
      component: resolve => require(['@/pages/help/about'], resolve),
      meta: {
        needSetPIN: true
      }
    },
    {
      path: '/help/digitalAsset',
      component: resolve => require(['@/pages/help/digitalAsset'], resolve),
      meta: {
        needSetPIN: true
      }
    },
    {
      path: '/trading/:pair?',
      name: 'trading',
      component: resolve => require(['@/pages/trading/index'], resolve),
      meta: {
        needSetPIN: true
      }
    },
    {
      path: '/tradeList',
      name: 'tradeList',
      component: resolve => require(['@/pages/trading/TradeList'], resolve)
    },
    {
      path: '/fiat/index/:pair?',
      name: 'fiat',
      component: resolve => require(['@/pages/fiat/index'], resolve),
      meta: {
        needSetPIN: true
      }
    },
    {
      path: '/fiat/userguide',
      component: resolve => require(['@/pages/fiat/userguide'], resolve)
    },
    {
      path: '/tteesstt',
      component: resolve => require(['@/pages/tteesstt/index.vue'], resolve)
    },
    {
      path: '/api',
      component: resolve => require(['@/pages/api/index'], resolve),
      meta: {
        needLogin: true,
        needSetPIN: true
      }
    },
    {
      path: '/api/list',
      component: resolve => require(['@/pages/api/list'], resolve)
    },
    {
      path: '/help',
      component: resolve => require(['@/pages/help/index'], resolve)
    },
    {
      path: '/help/list/:id?',
      name: 'hlist',
      component: resolve => require(['@/pages/help/list'], resolve)
    },
    {
      path: '/help/searchResult',
      component: resolve => require(['@/pages/help/searchResult'], resolve)
    },
    {
      path: '/help/feedback',
      component: resolve => require(['@/pages/help/feedback'], resolve)
    },
    {
      path: '/help/detail/:id?',
      name: 'hdetail',
      component: resolve => require(['@/pages/help/detail'], resolve)
    },
    {
      name: 'invitationIndex',
      path: '/invitation',
      component: resolve => require(['@/pages/invite/index'], resolve)
    },
    {
      name: 'invitationReferra',
      path: '/invitation/receive',
      component: resolve => require(['@/pages/invite/referra'], resolve)
    },
    {
      name: 'tutorial',
      path: '/help/tutorial',
      component: resolve => require(['@/pages/help/tutorial'], resolve)
    },

    /**
     * 添加IT页面路由
     * 
     */
    {
      name: '/activity',
      path: '/activity',
      redirect: '/activity/index',
      component: resolve => require(['@/pages/activity/index'], resolve),
      children: [
        { path: 'index', component:resolve => require(['@/pages/activity/activity'], resolve), name: 'activityIndex', },
        { path: 'subscription', component:resolve => require(['@/pages/activity/subscription'], resolve), name: 'activitysubscription', },
        { path: 'guideBanner', component:resolve => require(['@/pages/activity/guide'], resolve), name: 'activityguide', },
        { path: 'recordList', component:resolve => require(['@/pages/activity/record'], resolve), name: 'activityrecord', }
      ]
    },

  ]
})

router.beforeEach((to, from, next) => {
  // document.title
  // 需要登录的页面跳转
  if (to.meta.needLogin && !store.state.user.userInfo.userName) {

    next({path: '/user/login', query: to.query})
    return
  }
  // 需要pin的页面跳转
  if (to.meta.needSetPIN && store.state.user.userInfo.tempUserInfo && store.state.user.userInfo.tempUserInfo.NeedToSetSecurifyPwd) {

    next({path: '/safety/setPin'})
    return
  }

  if (store.state.user.userInfo.userName) {

    Http.post('Customer/CheckLogon', {
    }, {
      isDisposeCode: false
    })
    .then((res) => {

      if (res.StatusCode !== '200') {
        // 返回非200错误统一跳转至登陆界面
        next({path: '/user/login'})
        LoginService.clearUserInfo()
      }
    })
  }

  // if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
  //   location.href = '#/indexH5/index'
  //   return
  // }
  // 判断进入端口
  let versions = () => {
    let u = navigator.userAgent
     //  let app = navigator.appVersion
    return { // 移动终端浏览器版本信息
      ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
      android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, // android终端或uc浏览器
      iPhone: u.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器
      iPad: u.indexOf('iPad') > -1 // 是否iPad
    }
  }
  let checkMobile = () => {
    let browser = versions()
    if (browser.iPhone || browser.iPad || browser.ios || browser.android) {
      return true
    } else {
      return false
    }
  }
  let getPCOrMobile = () => {
    // 如果未匹配到路由
    if (to.matched.length === 0) {
      // 如果上级也未匹配到路由则跳转下载页面，如果上级能匹配到则转上级路由
      // from.fullPath ? next({ path: from.fullPath }) : next({path: '/download'})
      next({path: '/'})
    }

    // 旧下载页重定向到新下载页
    // 前者是history model，后者是hash模式
    if (to.path === '/indexH5/index' || to.hash === '#/indexH5/index') {
      location.href = `//m.${Config.mailDomain}/download`
      return
    }

    // 不取window.innerHTML，window.screen.width
    // 因为本站不写头部1比1，但是window弹出来的不是手机实际的px，会是近7、800的数字，换成screen后就是正确的360
    // 根据ua判断设备并不精准，但是判断小于750就一定是准确的
    // 在linux上根据ua会作为手机显示，所以判断条件为window.screen.width < 750 && checkMobile()
    if ((window.screen.width < 750 || (window.screen.width < 750 && checkMobile()))) { // && to.path !== '/indexH5/index'
      if (location.href.indexOf(`prewww.${Config.mailDomain}`) !== -1) {
        location.href = location.href.replace(`prewww.${Config.mailDomain}`, `prem.${Config.mailDomain}`)
      } else if (location.href.indexOf(`www.${Config.mailDomain}`) !== -1) {
        location.href = location.href.replace(`www.${Config.mailDomain}`, `m.${Config.mailDomain}`)
      } else if (location.href.indexOf(`${Config.mailDomain}`) !== -1) {
        location.href = location.href.replace(`${Config.mailDomain}`, `m.${Config.mailDomain}`)
      } else {
        location.href = `//m.${Config.mailDomain}`
      }
      // location.href = '//m.idcm.io'
      // next('/indexH5/index')
    } else {
      next()
    }
  }
  getPCOrMobile()
})

router.afterEach((to, from) => {
  // 销毁上页的通用弹框
  ModalApi.destroyAll()

  window.scrollTo(0, 0)

  // 由于是单页应用，使用前进后退按钮会重复$on，故会激发多次，但不在路由内的EventBus.$on调用不受此句代码控制，因此EventBus只能在路由且是vue里写
  EventBus.$off()

  // 由于index.html第一次加载时，会自动该url，如第一次加载"/"路径时，则这里不再统计"/"路径
  if (location.pathname !== to.path) {
    let pagePath = to.fullPath

    // 百度统计
    typeof _hmt !== 'undefined' && _hmt.push(['_trackPageview', pagePath])

    // 谷歌统计
    typeof gtag !== 'undefined' && gtag('config', 'UA-116615618-2', { // UA ID必须跟index.html谷歌统计代码的一样
      page_path: pagePath
    })

    // 友盟
    typeof _czc !== 'undefined' && _czc.push(['_trackPageview', pagePath])
  }
})

export default router
